package com.keyinong.caizhengting.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.activity.FanqiedingcanActivity;
import com.keyinong.caizhengting.activity.GoodsTwoSortActivity;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.keyinong.caizhengting.tools.GlideRoundTransform;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/18
 */
public class GoodsAdapter extends BaseAdapter {

    private Context mContext;
    private List<ShangpinEntity> mGoodsList;
    private HttpTools mHttpTools = null;
    private RequestOptions mRequestOptions;
    private int mGoodsNum = 0;

    public GoodsAdapter(Context context, List<ShangpinEntity> goodsList) {
        super();
        this.mContext = context;
        this.mGoodsList = goodsList;
        this.mRequestOptions = new RequestOptions()
                .centerCrop()
                .transform(new GlideRoundTransform(8));
    }

    @Override
    public int getCount() {
        return mGoodsList.size();
    }

    @Override
    public Object getItem(int i) {
        return mGoodsList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_goods, null);
            viewHolder = new ViewHolder();
            viewHolder.mIvGoodsImg = view.findViewById(R.id.iv_goods_img);
            viewHolder.mTvGoodsName = view.findViewById(R.id.tv_goods_name);
            viewHolder.mTvGoodsPrice = view.findViewById(R.id.tv_goods_price);
            viewHolder.mIvGoodsAdd = view.findViewById(R.id.iv_goods_add);
            viewHolder.mIvGoodsMinus = view.findViewById(R.id.iv_goods_minus);
            viewHolder.mTvGoodsNum = view.findViewById(R.id.tv_goods_number);
            viewHolder.mTvGoodsIntro = view.findViewById(R.id.tv_goods_intro);
            viewHolder.mIvGoodsLimit = view.findViewById(R.id.iv_goods_limit);
            viewHolder.mTvGoodsLimit = view.findViewById(R.id.tv_goods_limit);

            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        if (!"0".equals(mGoodsList.get(i).getDaylim())) {
            viewHolder.mIvGoodsLimit.setVisibility(View.VISIBLE);
            viewHolder.mTvGoodsLimit.setVisibility(View.VISIBLE);
            viewHolder.mTvGoodsLimit.setText(String.format("库存\n%s", mGoodsList.get(i).getStock()));
        }

        viewHolder.mTvGoodsName.setText(mGoodsList.get(i).getName());
        viewHolder.mTvGoodsIntro.setText(mGoodsList.get(i).getContent());

        viewHolder.mTvGoodsPrice.setText(mGoodsList.get(i).getPrice());
        viewHolder.mTvGoodsNum.setText(mGoodsList.get(i).getAmount());
        mGoodsNum = Integer.valueOf(mGoodsList.get(i).getAmount());

        Glide.with(mContext)
                .load(String.format("%s?imageView2/1/w/360/h/300", mGoodsList.get(i).getImage()))
                .apply(mRequestOptions)
                .into(viewHolder.mIvGoodsImg);

        viewHolder.mIvGoodsAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(mGoodsList.get(i).getPerlim()) - Integer.parseInt(mGoodsList.get(i).getBuyamount());
                int goodsNum = Integer.parseInt(viewHolder.mTvGoodsNum.getText().toString());
                goodsNum++;
                viewHolder.mIvGoodsAdd.setEnabled(false);
                addGoods(i, viewHolder.mTvGoodsNum, goodsNum, viewHolder.mIvGoodsAdd);
            }
        });

        viewHolder.mIvGoodsMinus.setOnClickListener(new View.OnClickListener() {
            int goodsNum;

            @Override
            public void onClick(View v) {
                int goodsNum = Integer.parseInt(viewHolder.mTvGoodsNum.getText().toString());
                goodsNum--;
                if (goodsNum < 0) {
                    Toast.makeText(mContext, "数量不能小于0", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (goodsNum == 0) {
                    deleteGoods(i);
                    goodsNum = 0;
                    viewHolder.mTvGoodsNum.setText("0");
                    return;
                }

                viewHolder.mTvGoodsNum.setText(String.format("%s", goodsNum));

                minusGoods(i, viewHolder.mTvGoodsNum, goodsNum);
            }
        });

        return view;
    }

    /**
     * 增加商品
     */
    private void addGoods(final int index, final TextView etGoodsNum, final int goodsNum, final ImageView ivGoodsAdd) {
        if (!NetWorkUtil.isNetwork(mContext)) {
            Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(etGoodsNum.getText().toString())) {
            etGoodsNum.setText(String.format("%s", 0));
        }
        SharedPreferences sp = mContext.getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (mHttpTools == null) {
            mHttpTools = new HttpTools(mContext);
        }

        mHttpTools.addgoodscat(token, mGoodsList.get(index).getId(), String.valueOf(goodsNum),
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            Log.i("zq", response.toString());
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            if (code) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
                                ivGoodsAdd.setEnabled(true);

                                etGoodsNum.setText(String.format("%s", goodsNum));
                                mGoodsNum = goodsNum;

                                setMsg("jia1", amount, index);
                                setMsg("zongjia1", total, 0);


                                setMsg1("jia1", amount, index);
                                setMsg1("zongjia1", total, 0);
                            } else {
                                ivGoodsAdd.setEnabled(true);
                                Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    /**
     * 减少商品
     */
    private void minusGoods(final int index, final TextView etGoodsNum, int goodsNum) {
        if (!NetWorkUtil.isNetwork(mContext)) {
            Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(etGoodsNum.getText().toString())) {
            etGoodsNum.setText(String.format("%s", 0));
            goodsNum = 0;
        }

        SharedPreferences sp = mContext.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (mHttpTools == null) {
            mHttpTools = new HttpTools(mContext);
        }
        mHttpTools.addgoodscat(token, mGoodsList.get(index).getId(), String.valueOf(goodsNum),
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            Log.i("info", response.toString());
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            int goodsNum = Integer.parseInt(etGoodsNum.getText().toString());
                            if (code) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");
                                int goodsNum2 = Integer.parseInt(etGoodsNum.getText().toString());

                                etGoodsNum.setText(String.valueOf(goodsNum));
                                mGoodsNum = goodsNum;
                                int lim = Integer.parseInt(mGoodsList.get(index).getStock());

                                setMsg("jian1", amount, index);
                                setMsg("zongjia1", total, 0);

                                setMsg1("jian1", amount, index);
                                setMsg1("zongjia1", total, 0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    /**
     * 移除商品
     */
    private void deleteGoods(final int index) {
        if (!NetWorkUtil.isNetwork(mContext)) {
            Toast.makeText(mContext, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = mContext.getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        if (mHttpTools == null) {
            mHttpTools = new HttpTools(mContext);
        }
        mHttpTools.remove(token, mGoodsList.get(index).getId(),
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        Log.e("zq", "删除------------" + response.toString());
                        try {
                            boolean code = response.getBoolean("code");
                            String msg = response.getString("msg");
                            if (code) {
                                JSONObject data = response.getJSONObject("data");
                                String amount = data.getString("amount");
                                String total = data.getString("total");

                                setMsg("qingchu1", amount, index);
                                setMsg("zongjia1", total, 0);

                                setMsg1("qingchu1", amount, index);
                                setMsg1("zongjia1", total, 0);
                            } else {
                                Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    private void setMsg(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
        GoodsTwoSortActivity.myhanler.sendMessage(message);
    }

    private void setMsg1(String sopt, String str, int index) {
        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putString("sopt1", sopt);
        bundle.putString("str1", str);
        bundle.putInt("index1", index);
        message.obj = bundle;
        FanqiedingcanActivity.myhanler.sendMessage(message);
    }

    public int getGoodsNum() {
        return mGoodsNum;
    }

    private class ViewHolder {
        /**
         * 图片
         */
        private ImageView mIvGoodsImg;
        /**
         * 商品名
         */
        private TextView mTvGoodsName;
        /**
         * 价格
         */
        private TextView mTvGoodsPrice;
        /**
         * 加
         */
        private ImageView mIvGoodsAdd;
        /**
         * 减
         */
        private ImageView mIvGoodsMinus;
        /**
         * 数量
         */
        private TextView mTvGoodsNum;

        private TextView mTvGoodsIntro;

        private ImageView mIvGoodsLimit;

        private TextView mTvGoodsLimit;
    }
}
